package com.edu.gcu.manager.service.impl;

import com.edu.gcu.manager.service.IIntegralService;
import com.edu.gcu.manager.vo.GiftRecordVo;
import com.edu.gcu.manager.vo.GiftVo;
import com.edu.gcu.system.common.Const;
import com.edu.gcu.system.common.ResponseCode;
import com.edu.gcu.system.common.ServerResponse;
import com.edu.gcu.system.dao.GiftMapper;
import com.edu.gcu.system.dao.GiftRecordMapper;
import com.edu.gcu.system.dao.UserMapper;
import com.edu.gcu.system.pojo.Gift;
import com.edu.gcu.system.pojo.GiftRecord;
import com.edu.gcu.system.pojo.User;
import com.edu.gcu.system.util.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author polo
 * @version V1.0
 * @description: 积分service接口实现类
 * @date 2018-02-20-12:22
 */

@Service("iIntegralService")
public class IIntegralServiceImpl implements IIntegralService {

    private Logger logger = LoggerFactory.getLogger(IIntegralServiceImpl.class);

    @Autowired
    private GiftMapper giftMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private GiftRecordMapper giftRecordMapper;

    private ServerResponse publicReturn(String msg, int resultCount) {
        if (resultCount > 0) {
            return ServerResponse.createByErrorMessage(msg + "成功!");
        }
        return ServerResponse.createByErrorMessage(msg + "失败!");
    }

    /*
     * 兑换商品
     * */
    @Override
    public ServerResponse delete(String id, String giftIds) {
        List<String> giftIdList = Splitter.on(";").splitToList(giftIds);
        for (String giftId : giftIdList) {
            Gift gift = new Gift();
            gift.setId(giftId);
            gift.setUpdateBy(id);
            gift.setStatus(Const.GiftStatusEnum.IS_DEL.getCode());
            int resultCount = giftMapper.updateByPrimaryKeySelective(gift);
            if (resultCount > 0) {
                continue;
            }
            return ServerResponse.createByErrorMessage("删除失败!");
        }
        return ServerResponse.createByErrorMessage("删除成功!");
    }

    @Override
    public ServerResponse update(String id, Gift gift) {
        int resultCount = giftMapper.updateByPrimaryKeySelective(gift);
        return this.publicReturn("更新", resultCount);
    }

    @Override
    public ServerResponse change(String id, String giftId, Integer status) {
        try {
            status = Const.GiftStatusEnum.codeOf(status).getCode();
        } catch (RuntimeException e) {
            logger.error("exception is ", e);
            return ServerResponse.createByErrorMessage("状态码错误,更新失败");
        }
        Gift gift = new Gift();
        gift.setId(giftId);
        gift.setUpdateBy(id);
        gift.setStatus(status);
        int resultCount = giftMapper.updateByPrimaryKeySelective(gift);
        return this.publicReturn("更新", resultCount);
    }

    @Override
    public ServerResponse add(String id, Gift gift) {
        gift.setId(UuidUtil.getUUID());
        gift.setStatus(Const.GiftStatusEnum.ON_SALE.getCode());
        gift.setCreateBy(id);
        gift.setUpdateBy(id);
        int resultCount = giftMapper.insertSelective(gift);
        return this.publicReturn("插入", resultCount);
    }

    @Override
    public ServerResponse detail(String id) {
        Gift gift = giftMapper.selectByPrimaryKey(id);
        if (gift != null) {
            GiftVo giftVo = this.assembleGiftVo(gift);
            return ServerResponse.createBySuccess(giftVo);
        }
        return ServerResponse.createByErrorMessage("查找失败!");
    }

    @Override
    public ServerResponse<PageInfo> list(String name, Integer status, String orderBy, Integer pageNum,
                                         Integer pageSize) {

        // 分页与排序
        PageHelper.startPage(pageNum, pageSize);
        if (StringUtils.isNotBlank(orderBy)) {
            if (Const.ProductGiftOrderBy.PRODUCT_GIFT_DESC_ASC.contains(orderBy)) {
                List<String> orderByList = Splitter.on("_").splitToList(orderBy);
                PageHelper.orderBy(orderByList.get(0) + " " + orderByList.get(1));
            }
        }

        List<Gift> giftList = giftMapper.selectList(name, status);
        List<GiftVo> giftVoList = Lists.newArrayList();
        for (Gift gift : giftList) {
            GiftVo giftVo = this.assembleGiftVo(gift);
            giftVoList.add(giftVo);
        }
        PageInfo pageInfo = new PageInfo<>(giftList);
        pageInfo.setList(giftVoList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    private GiftVo assembleGiftVo(Gift gift) {
        GiftVo giftVo = new GiftVo();
        BeanUtils.copyProperties(gift, giftVo);
        giftVo.setStatusDesc(Const.GiftStatusEnum.codeOf(gift.getStatus()).getValue());
        return giftVo;
    }

    /*
     * 兑换记录
     * */
    @Override
    public ServerResponse detailRecord(String id) {
        if (StringUtils.isBlank(id)) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode
                    .ILLEGAL_ARGUMENT.getDesc());
        }
        GiftRecord giftRecord = giftRecordMapper.selectByPrimaryKey(id);
        if (giftRecord != null) {
            GiftRecordVo giftRecordVoVo = this.assembleGiftRecordVo(giftRecord);
            if (giftRecordVoVo == null) {
                return ServerResponse.createByErrorMessage("商品不存在或用户不存在");
            }
            return ServerResponse.createBySuccess(giftRecordVoVo);
        }
        return ServerResponse.createByErrorMessage("查找失败!");
    }

    @Override
    public ServerResponse<PageInfo> listRecord(String name, String orderBy, Integer pageNum, Integer pageSize) {
        // 分页与排序
        PageHelper.startPage(pageNum, pageSize);
        if (StringUtils.isNotBlank(orderBy)) {
            if (Const.RecordOrderBy.RECORD_DESC_ASC.contains(orderBy)) {
                List<String> orderByList = Splitter.on("_").splitToList(orderBy);
                PageHelper.orderBy(orderByList.get(0) + " " + orderByList.get(1));
            }
        }

        List<GiftRecord> giftRecordList = giftRecordMapper.selectList(name);
        List<GiftRecordVo> giftRecordVoList = Lists.newArrayList();
        for (GiftRecord giftRecord : giftRecordList) {
            GiftRecordVo giftRecordVoVo = this.assembleGiftRecordVo(giftRecord);
            if (giftRecordVoVo == null) {
                return ServerResponse.createByErrorMessage("商品不存在或用户不存在");
            }
            giftRecordVoList.add(giftRecordVoVo);
        }
        PageInfo pageInfo = new PageInfo<>(giftRecordList);
        pageInfo.setList(giftRecordVoList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    private GiftRecordVo assembleGiftRecordVo(GiftRecord giftRecord) {
        GiftRecordVo giftRecordVoVo = new GiftRecordVo();
        Gift gift = giftMapper.selectByPrimaryKey(giftRecord.getGiftId());
        if (gift == null) {
            return null;
        }
        User user = userMapper.selectByPrimaryKey(giftRecord.getCustomerId());
        if (user == null) {
            return null;
        }
        BeanUtils.copyProperties(giftRecord, giftRecordVoVo);
        giftRecordVoVo.setCreateTime(giftRecord.getDate());
        giftRecordVoVo.setSex(user.getSex() == 1 ? "男" : "女");
        giftRecordVoVo.setUsername(user.getNickname());
        return giftRecordVoVo;
    }
}
